<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Table, TableColumn } from '@/components/Table'
import { Icon } from '@/components/Icon'
import { BaseButton } from '@/components/Button'
import { ElMessage } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'

import { useTable } from '@/hooks/web/useTable'
import { reactive, unref, ref, computed } from 'vue'
import { GetMarketRatioListApi, SaveMarketRatioListApi } from '@/api/user'
import { useI18n } from '@/hooks/web/useI18n'
import { cloneDeep } from 'lodash-es'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const { data, count } = await GetMarketRatioListApi({
      pageNo: unref(currentPage),
      pageSize: unref(pageSize)
    })
    return {
      list: data,
      total: count
    }
  }
})
const { loading, dataList, currentPage, pageSize } = tableState
const { getList } = tableMethods

const columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index'
  },
  {
    field: 'advertisingCommissionRate',
    label: '大盘比例(%)'
  },
  {
    field: 'superpositionRuleRate1',
    label: '广告收益叠加比例1(%)'
  },
  {
    field: 'superpositionRuleRate2',
    label: '广告收益叠加比例2(%)'
  },
  {
    field: 'superpositionRuleRate3',
    label: '广告收益叠加比例3(%)'
  },
  {
    field: 'intervalTime',
    label: '两次广告间隔时间(秒)'
  },
  {
    field: 'advertisingEarningsMin',
    label: '广告最小收益'
  },
  {
    field: 'advertisingEarningsMax',
    label: '广告最大收益'
  },
  {
    field: 'advertisingCount',
    label: '每日广告条数限制'
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 180,
    slots: {
      default: ({ row }) => {
        return (
          <BaseButton type="primary" size="small" onClick={() => onOpenDialog(row)}>
            {{
              icon: () => <Icon size={20} icon="carbon:edit" />,
              default: () => '编辑'
            }}
          </BaseButton>
        )
      }
    }
  }
])

// Dialog
const visible = ref(false)
const isEdit = ref(false)
const disabled = ref(false)
const title = computed(() => (isEdit.value ? '编辑' : '新增'))
//Form
const { formRegister, formMethods } = useForm()
const { getFormData, setValues, getElFormExpose } = formMethods

const formData = ref<any>({})

const uploadLoading = ref(false)

const { required } = useValidator()

const onBeforeClose = (done) => {
  if (uploadLoading.value) {
    // abortUploadFile()
  }
  done()
}

const schema = computed<FormSchema[]>(() => [
  {
    field: 'advertisingCommissionRate',
    label: '大盘比例(%)',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'superpositionRuleRate1',
    label: '广告收益叠加比例1(%)',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'superpositionRuleRate2',
    label: '广告收益叠加比例2(%)',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'superpositionRuleRate3',
    label: '广告收益叠加比例3(%)',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'intervalTime',
    label: '两次广告间隔时间(秒)',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'advertisingEarningsMin',
    label: '广告最小收益',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'advertisingEarningsMax',
    label: '广告最大收益',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'advertisingCount',
    label: '每日广告条数限制',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  }
])
// 新增
const onOpenDialog = async (row) => {
  visible.value = true
  if (row) {
    // 编辑
    isEdit.value = true
    setValues(cloneDeep(row))
  } else {
    // 新增
    isEdit.value = false
  }
}
// 重置
const onReset = async () => {
  const elFormExpose = await getElFormExpose()
  elFormExpose?.resetFields()
}
// 立即提交
const onFormSubmit = async () => {
  const elFormExpose = await getElFormExpose()
  elFormExpose?.validate(async (isValid) => {
    if (!isValid) {
      ElMessage.warning('请填写完整信息')
      return
    } else {
      disabled.value = true
      const formData = await getFormData()
      SaveMarketRatioListApi({ ...formData })
        .then(() => {
          visible.value = false
          ElMessage.success('操作成功！')
          getList()
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          disabled.value = false
        })
    }
  })
}
</script>

<template>
  <ContentWrap title="比例分配">
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="columns"
      :data="dataList"
      row-key="id"
      :loading="loading"
      sortable
      headerAlign="center"
      align="center"
      @register="tableRegister"
    />
    <!-- 新增提示-弹窗 -->
    <Dialog
      v-model="visible"
      :title="title"
      width="600"
      maxHeight="500px"
      :close-on-click-modal="false"
      :before-close="onBeforeClose"
    >
      <Form
        class="w-[500px] ml-[auto] mr-[auto]"
        labelPosition="top"
        v-loading="disabled"
        :schema="schema"
        :model="formData"
        :isCol="false"
        @register="formRegister"
      />
      <template #footer>
        <div class="text-center mb-[16px]">
          <BaseButton @click="onReset">重置</BaseButton>
          <BaseButton type="primary" :disabled="disabled" debounce @click="onFormSubmit"
            >立即提交</BaseButton
          >
        </div>
      </template>
    </Dialog>
  </ContentWrap>
</template>
